package com.chidopi.market.bookstore.actions;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;

import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.chidopi.cdf.exception.CdfException;
import com.chidopi.cdf.service.IBaseService;
import com.chidopi.cdf.struts1actions.StandardOperatorAction;
import com.chidopi.cdf.util.ModelContextFactory;
import com.chidopi.market.bookstore.domain.BookCities;
import com.chidopi.market.bookstore.domain.Subscriptions;
import com.chidopi.market.util.JsonDateValueProcessor;
import com.chidopi.market.util.MessageHandler;

public class SubscriptionsAction extends StandardOperatorAction<Subscriptions>{
	
	private static Logger logger = LoggerFactory.getLogger(SubscriptionsAction.class);
	
	private IBaseService<Subscriptions> baseService;
	
	private IBaseService<BookCities> cityService;
	
	public SubscriptionsAction(){
		this("");
	}
	
	@SuppressWarnings("unchecked")
	public SubscriptionsAction(String entryURL) {
		this.entryURL = entryURL;
		try {
			this.baseService = (IBaseService<Subscriptions>)
				ModelContextFactory.get("subscriptionsService", IBaseService.class);
			this.cityService = (IBaseService<BookCities>)
				ModelContextFactory.get("bookCitiesService", IBaseService.class);
		} catch (Exception e) {
			this.baseService = null;
			logger.warn("initial", e);
		}
	}
	
	public ActionForward init(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		DynaBean dynaForm = (DynaBean) form;
		dynaForm.set("vo", null);
		dynaForm.set("op", null);
		List<BookCities> list = cityService.find(null);
		dynaForm.set("cities", list);
		logger.info("cities:" + list);
		return mapping.findForward("success");
	}
	
	public ActionForward back(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		return mapping.findForward("success");
	}
	
	private static final String[] conditions = {"id", "name", "city_id" , "start_time", "end_time", "apply_os", "enable_flag"};
	public ActionForward query(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		if (null == this.baseService) return mapping.findForward("error");
		StringBuffer sql = new StringBuffer();
		ArrayList<String> args = new ArrayList<String>();
		for (String cond : conditions) {
			String value = (String) request.getParameter(cond);
			if (value == null || value.trim().equals("")) continue;
			logger.debug(cond + "=" + value);
			
			if(cond.endsWith("_flag") && request.getParameterValues(cond).length >1){
				 continue;
			}
			
			if (sql.length() > 1) sql.append("and ");
			if (cond.equals("city_id")) {
				sql.append( cond + " = ?");
				args.add(value);
			}else if( cond.equals("enable_flag")){
				sql.append("a.enable_flag = ?");
				args.add(value);
			}else if (cond.endsWith("_time")){
			    sql.append(cond + " >= DATE_FORMAT( ? ,'%Y-%m-%d 00:00:00') ");	
			    sql.append(" and ");
			    sql.append(cond + " <= DATE_FORMAT( ? ,'%Y-%m-%d 23:59:59') ");
			    args.add(value);
			    args.add(value);
			}else if (cond.equals("id")){
				sql.append("a.id like ?");
				args.add("%" + value +"%");
			} else {
				sql.append(cond + " like ?");
				args.add("%" + value +"%");
			}
		}
		logger.debug("sql=" + sql.toString());
		List<Subscriptions> list = this.baseService.find(sql.toString(),args.toArray());
		logger.debug("size=" + list.size());
		
		JsonConfig jsonConfig = new JsonConfig(); 
		jsonConfig.registerJsonValueProcessor(Date.class,new JsonDateValueProcessor()); 

		JSONArray json = JSONArray.fromObject(list,jsonConfig);

		PrintWriter out=response.getWriter();
		logger.debug(json.toString());
        out.println(json);
        out.flush();
		return null;
	}
	
	public ActionForward delete(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String id = request.getParameter("id");
		logger.debug("id=" + id);
		Subscriptions t = this.baseService.findById(new Integer(id));
		if (null == t) {
			logger.warn("Subscriptions[id={}] is deleted!!", id);
			return mapping.findForward("err");
		}
		DynaBean dynaForm = (DynaBean) form;
		dynaForm.set("op", "delete");
		dynaForm.set("vo", t);
		List<BookCities> list = cityService.find(" ENABLE_FLAG = 'Y'");
		dynaForm.set("cities", list);
		return mapping.findForward("success");
	}

	public ActionForward insert(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String id = request.getParameter("id");
		logger.debug("id=" + id);
		Subscriptions t = this.baseService.findById(id);
		if (null == t) t = new Subscriptions();
		DynaBean dynaForm = (DynaBean) form;
		dynaForm.set("op", "insert");
		dynaForm.set("vo", t);
		List<BookCities> list = cityService.find(" ENABLE_FLAG = 'Y'");
		dynaForm.set("cities", list);
		return mapping.findForward("success");
	}

	public ActionForward update(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String id = request.getParameter("id");
		logger.debug("id=" + id);
		Subscriptions t = this.baseService.findById(id);
		if (null == t) {
			logger.warn("ContextProvider[id={}] is deleted!!", id);
			return mapping.findForward("err");
		}
		DynaBean dynaForm = (DynaBean) form;
		dynaForm.set("op", "update");
		dynaForm.set("vo", t);
		List<BookCities> list = cityService.find(" ENABLE_FLAG = 'Y'");
		dynaForm.set("cities", list);
		return mapping.findForward("success");
	}

	public ActionForward save(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String op = request.getParameter("op");
		Integer userId = (Integer) request.getSession().getAttribute("user_id");
		logger.debug("op=" + op);
		Subscriptions t = new Subscriptions();
		try {
			DynaBean dynaForm = (DynaBean) form;
			PropertyUtils.copyProperties(t, dynaForm.get("vo"));
			logger.debug(t.getId() + ":" + t.getName() + "/" +t.getBookCity().getId());
		} catch (Exception e) {
			logger.warn("PropertyUtils", e);
			return mapping.findForward("err");
		}

		int ret = -1;
		if ("insert".equals(op)) {
			t.setCreate_by(userId);
			ret = this.baseService.insert(t);
		} else if ("update".equals(op)) {
			t.setUpdate_by(userId);
			ret = this.baseService.update(t);
		} else if ("delete".equals(op)) {
			t.setUpdate_by(userId);
			try{
				ret = this.baseService.delete(t);
			}catch(CdfException cex){
				MessageHandler.getInstance().processError(request, cex.getMessage());
			}			
		}
		if (ret > -1) {
			request.setAttribute("entryURL", entryURL);
			return mapping.findForward("success");
		}else {
			return mapping.findForward("err");
		}
	}

}
